﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Contact.API.Data.Core;
using Contact.API.Data.Interface;
using Contact.API.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Contact.API.Controllers
{
    [Produces("application/json")]
    [Route("api/Contacts/[action]")]
    public class ContactsController : BaseController
    {
        private readonly IContactRepository _contactRepository;
        private readonly IContactApplyRequestRepository _contactApplyRequestRepository;
        private readonly IUserService _userService;
        public ContactsController(IContactRepository contactRepository,
            IContactApplyRequestRepository contactApplyRequestRepository,
            IUserService userService)
        {
            _contactRepository = contactRepository;
            _userService = userService;
            _contactApplyRequestRepository = contactApplyRequestRepository;
        }
        [HttpGet]
        public async Task<IActionResult> GetRequestsAsync(CancellationToken cancellationToken)
        {
            var list = await _contactApplyRequestRepository.GetContactRequestListAsync(UserIdentity.UserId, cancellationToken);
            return Json(list);
        }
        [HttpPost]
        public async Task<IActionResult> AddRequestAsync(int userId, CancellationToken cancellationToken)
        {
            var user = await _userService.GetBaseUserInfoAsync(UserIdentity.UserId);
            if (user == null)
            {
                throw new Exception("操作异常");
            }
            var rt = await _contactApplyRequestRepository.AddRequestAsync(new ContactApplyRequest()
            {
                ApplierId = UserIdentity.UserId,
                UserId = userId,
                Avatar = user.Avatar,
                Company = user.Company,
                CreateTime = DateTime.Now,
                Name = user.Name,
                Title = user.Title
            }, cancellationToken);
            return Ok();
        }
        [HttpPost]
        public async Task<IActionResult> ApproveRequestAsync(int applierId, CancellationToken cancellationToken)
        {
            var rt = await _contactApplyRequestRepository.ApproveRequestAsync(applierId, UserIdentity.UserId,cancellationToken);
            return Ok();
        }
    }
}